/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 6/15/13
 * Time: 12:24 AM
 */
package com.google.code.bankagregator.core;

import com.google.code.bankagregator.dao.ScheduleDAO;
import com.google.code.bankagregator.entities.ScheduleEntity;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Cron. First run one minute after deploy.
 * Schedule time managed by persistent values.
 */
@Singleton
@Startup
public class CronJob {

    private final Logger log = Logger.getLogger(CronJob.class.getName());
    private Integer scheduleTime = 0;

    @EJB
    UpdateManager updateManager;
    @EJB
    ScheduleDAO scheduleDAO;
    @Resource
    TimerService timers;

    /**
     * Check for changes of "scheduletime", which specify delay between cron calls.
     *
     * @return true if parameter "scheduletime" was changed after last cron call.
     */
    public boolean isScheduleChanged() {
        ScheduleEntity autoSchedule = scheduleDAO.read("scheduletime");
        if (autoSchedule == null ||
                scheduleTime.toString().equals(autoSchedule.getParamValue())) {
            return false;
        }
        return true;
    }

    /**
     * Cron task of update date.
     *
     * @param timer
     */
    @Schedule(minute = "*/1", hour = "*")
    @Timeout
    public void runCron(Timer timer) {
        if (isScheduleChanged()) {
            ScheduleEntity autoSchedule = scheduleDAO.read("scheduletime");
            scheduleTime = Integer.valueOf(autoSchedule.getParamValue());
            ScheduleExpression expr = timer.getSchedule();
            expr.minute("*/" + scheduleTime.toString());
            timers.createCalendarTimer(expr);
            timer.cancel();
            log.log(Level.INFO, "Cron schedule changed to " + "*/" + scheduleTime.toString());
        }
        log.log(Level.INFO, "Cron running at " + new Date().toString());
        // updateManager.updateProducts();
    }

    /**
     * Startup tasks
     */
    @PostConstruct
    public void runOnStart() {
        ScheduleEntity schedule = new ScheduleEntity();
        schedule.setParamName("scheduletime");
        schedule.setParamValue("15");
        scheduleDAO.update(schedule);
    }

}
